package com.ssm.web;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.ssm.entity.User;
import com.ssm.service.UserService;

@Controller
public class LoginController {

	@Resource(name = "userService")
	private UserService userService;

	/**
	 * 这是登录首页
	 * 
	 * @param mv
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	private ModelAndView index() {
		return new ModelAndView("login", "command", new User());
	}

	/**
	 * 这里是获取form表单获取数据然后扔到mapper的xml去查询数据库是否对的，对的才能返回正确的有内容的页面
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/index", method = RequestMethod.POST)
	private ModelAndView login(User user, HttpSession seesion) {
		ModelAndView mv = new ModelAndView();
		User user1 = userService.login(user.getUsername(), user.getPassword());
		if (user1 != null) {
			seesion.setAttribute("username", user.getUsername());
			mv.addObject("user", user1);
			mv.setViewName("index");
			System.out.println(user1.toString());
			return mv;
		} else {
			mv.addObject("user", "false");
			mv.setViewName("index");
			return mv;
		}

	}

	/**
	 * 这是添加用户的页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/addUserIndex", method = RequestMethod.GET)
	private ModelAndView addUserIndex() {
		return new ModelAndView("add", "command", new User());
	}

	/**
	 * 这里是添加用户的方法
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	private ModelAndView add(User user) {
		ModelAndView mv = new ModelAndView();
		int user1 = userService.addUser(user.getUsername(), user.getPassword());
		if (user1 == 1) {
			mv.addObject("add", "添加用户成功");
			mv.setViewName("addindex");
			return mv;
		} else {
			mv.addObject("add", "添加用户失败");
			mv.setViewName("addindex");
			return mv;
		}
	}

	@RequestMapping(value = "/updateUserIndex", method = RequestMethod.GET)
	private ModelAndView updateUserIndex() {
		ModelAndView mv = new ModelAndView();
		mv.addObject("command", new User());
		mv.setViewName("update");
		return mv;
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	private ModelAndView update(User user, HttpSession session) {
		ModelAndView mv = new ModelAndView();
		Object username = session.getAttribute("username");
		int update = userService.updateUser(username.toString(), user.getPassword());
		if (update == 1) {
			mv.addObject("update", "修改成功");
			mv.setViewName("updateindex");
			return mv;
		} else {
			mv.addObject("update", "修改失败");
			mv.setViewName("updateindex");
			return mv;
		}
	}

}
